/************************************************************************
 * SMLib - State Model Library
 * Copyright (C) 2012-2013 Ali Khalili (khalili_DOT_ir_@SIGN_gmail_DOT_com)
 * **********************************************************************
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License (LGPL) published 
 * by the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version. This program is distributed without any
 * warranty. See the GNU Lesser General Public License for more details. 
 * ***********************************************************************
 * File         :     
 * Description  :     
 * Change log   :     
 * To Do        :
 ************************************************************************/
using System;
using SMLib.Automata.Base;

namespace SMLib
{
	public class SUL_MM_WrapperProxy: SMLib.Automata.MM.IBlackBox_MM
	{
		TcpHelper helper;
		Alphabet alphabet;

		public SUL_MM_WrapperProxy (int port)
		{
			helper = new TcpHelper ("localhost", port);
			alphabet = null;
			helper.Init ();
		}
		
		public void Close()
		{
			helper.Close();
		}
		
		#region IBlackBox_MealyMachine implementation
		public void Reset ()
		{
			
			TcpHelper.PACKET p = new TcpHelper.PACKET ();
			p.TYPE = 1;
			//Console.WriteLine ("Send reset. Packet is: " + p.ToString ());
			//TcpHelper.PACKET q = 
			helper.SendPacket (p);
			//Console.WriteLine ("Answer is: " + q.ToString ());
			//return new SMLib.Automata.Base.StringSymbol(q.CONTENT);
		}

		public SMLib.Automata.Base.ISymbol Step (SMLib.Automata.Base.ISymbol input)
		{
			TcpHelper.PACKET p = new TcpHelper.PACKET ();
			p.CONTENT = input.ToString ();
			p.TYPE = 102;
			//Console.WriteLine ("Send input. Packet is: " + p.ToString ());
			TcpHelper.PACKET q = helper.SendPacket (p);
			//Console.WriteLine ("Answer is: " + q.ToString ());
			if (q.CONTENT == "")
				return null;
			
			return new SMLib.Automata.Base.StringSymbol (q.CONTENT);
		}

		public SMLib.Automata.Base.Alphabet InputAlphabet {
			get {
				if (alphabet == null) {
					TcpHelper.PACKET p = new TcpHelper.PACKET ();
					p.TYPE = 8;
					//Console.WriteLine ("Send ASK ALPHABET. Packet is: " + p.ToString ());
					TcpHelper.PACKET q = helper.SendPacket (p);
					//Console.WriteLine ("Answer is: " + q.ToString ());
					String [] symbs = q.CONTENT.Split (';');
					alphabet=new Alphabet();
					foreach (string sym in symbs)
					{	if(sym=="")
							continue;					
						alphabet.AddSymbol (new StringSymbol (sym));
						//Console.Write("Alphabet has "+sym);
					}
					return alphabet;	
				} else
					return alphabet;
			}
		}
		#endregion
	}
}

